package com.a1573595.musicplayer.dbHelper

import android.content.Context
import android.util.Log
import com.a1573595.musicplayer.R
import com.a1573595.musicplayer.model.Music
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader

class Music_DatabaseInitializer(private val context: Context) {
    fun initialize() {
        val dbHelper = OnLineMusicDatabaseHelper(context)

        // JSON 数据
        val json = readJsonFromRaw(R.raw.musicdata)

        // 使用 Gson 解析 JSON 并存储到数据库
        val gson = Gson()
        val musicList: List<Music> = gson.fromJson(json, object : TypeToken<List<Music>>() {}.type)
        musicList.forEach { music ->
            Log.d("MusicDebug", "Music: $music")
            dbHelper.insertMusic(music)
        }

        Log.d("DatabaseInitializer", "Database initialized with music.")
        dbHelper.close() // 关闭数据库连接
    }

    private fun readJsonFromRaw(resourceId: Int): String {
        val inputStream = context.resources.openRawResource(resourceId)
        val reader = BufferedReader(InputStreamReader(inputStream))
        val builder = StringBuilder()
        reader.forEachLine { builder.append(it) }
        reader.close()
        return builder.toString()
    }
}